package cn.xiuxius.askbox.service.impl;

import cn.xiuxius.askbox.common.constant.RedisConstant;
import cn.xiuxius.askbox.common.utils.MailUtil;
import cn.xiuxius.askbox.common.utils.RandomUtil;
import cn.xiuxius.askbox.pojo.dto.common.RegisterDTO;
import cn.xiuxius.askbox.pojo.vo.CaptchaVO;
import cn.xiuxius.askbox.pojo.vo.RegisterVO;
import cn.xiuxius.askbox.service.ICommonService;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CommonServiceImpl implements ICommonService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private RandomUtil randomUtil;

    @Override
    public CaptchaVO getCaptcha() {
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        String resultStr = captcha.text();
        Double result = Double.parseDouble(resultStr);
        UUID captchaUuid = UUID.randomUUID();
        String captchaKey = RedisConstant.LOGIN_CAPTCHA_KEY + captchaUuid;
        redisTemplate.opsForValue().set(captchaKey, result,120, TimeUnit.SECONDS);
        return new CaptchaVO(captchaUuid.toString(), captcha.toBase64());
    }

    @Override
    public RegisterVO getRegisterCaptcha(RegisterDTO registerDTO) {
        String captchaCode = randomUtil.getRandomNum(6);
        mailUtil.sendMail(registerDTO.getEmail(), "注册验证码", "验证码为：" + captchaCode);
        UUID uuid = UUID.randomUUID();
        redisTemplate.opsForValue().set(RedisConstant.EMAIL_CAPTCHA_KEY + uuid, captchaCode, 120, TimeUnit.SECONDS);
        return new RegisterVO(uuid.toString());
    }
}
